package com.company.project.utils;

import java.util.Calendar;

/**
 * 身份证校验
 *
 * @author xuew
 */
public class IDCardUtil {
    public static final int MALE = 0;
    public static final int FEMALE = 1;

    /**
     * 校验身份证最后第二位，单数为男双数为女
     *
     * @param sex
     * @param id
     * @return
     */
    public static boolean validIdAndSex(int sex, String id) {
        if (!validId(id)) {
            return false;
        }
        int last = Integer.valueOf(id.substring(id.length() - 2, id.length() - 1));
        return (sex == MALE && last % 2 == 1) || (sex == FEMALE && last % 2 == 0);
    }


    /**
     * 从身份证得到年龄
     *
     * @param id
     * @return
     */
    public static int getAgeFromIdCard(String id) {
        if (!validId(id)) {
            throw new IllegalArgumentException("非法身份证");
        }
        int iAge = 0;
        Calendar cal = Calendar.getInstance();
        String year = id.substring(6, 10);
        int iCurrYear = cal.get(Calendar.YEAR);
        iAge = iCurrYear - Integer.valueOf(year);
        return iAge;
    }

    /**
     * 从身份证得到年龄
     *
     * @param id
     * @return
     */
    public static String getAgeStringFromIdCard(String id) {
        if (!validId(id)) {
            return "";
        }
        int iAge = 0;
        Calendar cal = Calendar.getInstance();
        String year = id.substring(6, 10);
        int iCurrYear = cal.get(Calendar.YEAR);
        iAge = iCurrYear - Integer.valueOf(year);
        return String.valueOf(iAge);
    }

    /**
     * 校验身份证是否是合法的
     *
     * @param id
     * @return
     */
    public static boolean validId(String id) {
        if (id == null || id.length() != 18) {
            return false;
        }
        return true;
    }
}
